package com.newland.zxy.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : zhangxuyuan
 * @Project: springsecurity
 * @Package com.newland.zxy.config
 * @date Date : 2021年02月08日 10:44
 *
 *
 * 这是自定义的过滤器，负责从请求中获取token,进行认证
 */
public class JwtSecurityFilter extends BasicAuthenticationFilter {


    @Autowired
    AuthenticationManager manager;

    public JwtSecurityFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取token
        String access_token = request.getParameter("access_token");

        if(access_token==null)
        {
            System.out.println("token==null");
            SecurityContextHolder.getContext().setAuthentication(null);
            chain.doFilter(request,response);
            return;
        }
        String uid = MySecurityUtils.checkToken(access_token);
        if(uid==null)
        {
            System.out.println("token invalid");
            SecurityContextHolder.getContext().setAuthentication(null);
            chain.doFilter(request,response);
        }
        else
        {
            System.out.println(uid);
            Authentication auth= new UsernamePasswordAuthenticationToken(uid,
            null,null);
            //用认证控制器认证一下
            Authentication authenticate = manager.authenticate(auth);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            chain.doFilter(request,response);
        }

    }

    @Override
    protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
        MySecurityUtils.responseForbiden(response);
    }
}
